package com.city.java.orders.pojo.entity;

import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.time.LocalDateTime;

/**
 * 订单实体类
 */
@Data
public class Orders {
    private Long orderId;
    private Long productId;
    private Long userId;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime createdAt;
    private PaymentStatus paymentStatus;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime paymentTime;

    private Integer pageNum;
    private Integer pageSize;
    private String productName;

    /**
     * 支付状态枚举 - 对应数据库 ENUM('pending', 'paid', 'failed')
     */
    public enum PaymentStatus {
        PENDING("pending"),
        PAID("paid"),
        FAILED("failed");

        private final String value;

        PaymentStatus(String value) {
            this.value = value;
        }

        public String getValue() {
            return value;
        }

        public static PaymentStatus fromValue(String value) {
            for (PaymentStatus status : values()) {
                if (status.value.equalsIgnoreCase(value)) {
                    return status;
                }
            }
            throw new IllegalArgumentException("Invalid payment status: " + value);
        }

        @Override
        public String toString() {
            return this.value;
        }
    }

    /**
     * 设置支付状态时自动处理支付时间
     */
    public void setPaymentStatus(PaymentStatus paymentStatus) {
        this.paymentStatus = paymentStatus;
        // 如果支付状态为已支付且支付时间为空，则设置为当前时间
        if (paymentStatus == PaymentStatus.PAID && this.paymentTime == null) {
            this.paymentTime = LocalDateTime.now();
        }
        // 如果支付状态不是已支付，则清空支付时间
        else if (paymentStatus != PaymentStatus.PAID) {
            this.paymentTime = null;
        }
    }
}
